﻿// (c) Copyright Michael Antonio.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Subsonic.Data;
using MichMan.Utilities.Requests;
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization;
using MichMan.Utilities;
using Subsonic.Resources;

namespace Subsonic.Pages
{
    public partial class ServerSettingsPage : PhoneApplicationPage
    {
        public ServerSettingsPage()
        {
            InitializeComponent();
        }

        int _serverIndex = 0;

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);


            SubsonicSettings settings = SubsonicSettings.Instance;
            SubsonicServer server = settings.ActiveServer;

            if (NavigationContext.QueryString.TryGet<int>("index", out _serverIndex))
            {
                _serverIndex = Math.Max(0, _serverIndex);
                _serverIndex = Math.Min(_serverIndex, SubsonicSettings.Instance.Servers.Count - 1);
                server = SubsonicSettings.Instance.Servers[_serverIndex];
            }

            ServerName.Text = server.Name;
            ServerAddress.Text = server.ServerAddress;
            UserName.Text = server.Username;
            Password.Password = server.Password;
            JukeboxSwitch.IsChecked = server.Jukebox;
            JukeboxSwitch.Content = (JukeboxSwitch.IsChecked.Value ? "{jukebox_mode_on}" : "{jukebox_mode_off}").StaticResource();
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_pingRequest != null)
            {
                _pingRequest.CancelAsync();
            }

            SaveSettings();

            base.OnNavigatedFrom(e);
        }

        SubsonicServer Server
        {
            get
            {
                SubsonicServer server = new SubsonicServer();
                server.Name = ServerName.Text;
                server.ServerAddress = ServerAddress.Text;
                server.Username = UserName.Text;
                server.Password = Password.Password;
                server.Jukebox = JukeboxSwitch.IsChecked.HasValue ? JukeboxSwitch.IsChecked.Value : false;

                return server;
            }
        }

        protected void SaveSettings()
        {
            SubsonicSettings settings = SubsonicSettings.Instance;
            settings.Servers[_serverIndex] = Server;

            SubsonicSettings.Save();
        }

        IRequest _pingRequest = null;
        // TODO:  Add UI to show that we're waiting for a response.
        private void Ping_Click(object sender, RoutedEventArgs e)
        {
            if (_pingRequest == null)
            {
                if (this.JukeboxSwitch.IsChecked.Value)
                {
                    _pingRequest = new JukeboxControlRequest(JukeboxAction.get) { Server = Server };
                }
                else
                {
                    _pingRequest = new PingRequest() { Server = Server };
                }
                _pingRequest.RunRequestCompleted += new MichMan.Utilities.Requests.RunRequestCompletedEventHandler(pingRequest_RunRequestCompleted);
                _pingRequest.RunRequestAsync();
            }
            this.IsEnabled = false;
        }

        void pingRequest_RunRequestCompleted(object sender, MichMan.Utilities.Requests.RunRequestCompletedEventArgs e)
        {
            this.IsEnabled = true;
            _pingRequest = null;
            SubsonicRequest pingRequest = (SubsonicRequest)sender;

            if (pingRequest.RequestStatus == RequestStatus.Cancelled)
            {
                return;
            }
            else if (pingRequest.RequestStatus == RequestStatus.Succeeded)
            {
                if (pingRequest.Response.Error != null)
                {
                    MessageBox.Show(pingRequest.Response.Error.Message);
                }
                else
                {
                    MessageBox.Show("{settings_testing_ok}".StaticResource());
                }
            }
            else
            {
                string errorStr = "{background_task_network_error}";
                if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    errorStr = "{background_task_no_network}";
                }

                MessageBox.Show(String.Format("{0}  {1}", "{settings_connection_failure}".StaticResource(), errorStr.StaticResource()));
            }
        }

        private void ToggleSwitch_Unchecked(object sender, RoutedEventArgs e)
        {
            ToggleSwitch jbSwitch = (ToggleSwitch)sender;
            jbSwitch.Content = (jbSwitch.IsChecked.Value ? "{jukebox_mode_on}" : "{jukebox_mode_off}").StaticResource();
        }
    }
}